import * as React from "react";
import { connect } from "react-redux";
import { homeActions} from '../../../../../store/home.js';
import { Cell, Column, Table } from "@blueprintjs/table";
import { AppToaster} from "../../../../../component/Toast";
import Edit from '../Edit';
import Delete from '../Delete';
import axios from '../../../../../config/axios';
import {host} from '../../../../../config/host';
import {HandlePostData, handleEditData} from '../../../../../config/handleData';
import { Icon  } from "@blueprintjs/core";

import './index.less';

class TableWrapper extends React.PureComponent {
    constructor(props) {
        super(props);
        this.setTable = this.setTable.bind(this);
        this.cellRenderer = this.cellRenderer.bind(this);
        this.setColumn = this.setColumn.bind(this);
        this.setEditDeleteCell = this.setEditDeleteCell.bind(this);
        this.stopBubble = this.stopBubble.bind(this);
        this.handleEditClose = this.handleEditClose.bind(this);
        this.handleDeleteClose = this.handleDeleteClose.bind(this);
        this.handleDeleteOk = this.handleDeleteOk.bind(this);
        this.inputChange = this.inputChange.bind(this);
        this.inputEnter = this.inputEnter.bind(this);
        document.onkeydown = this.inputEnter.bind(this);
        this.state = {
            value: [],
            editIsOpen: false,
            editAttributes: [],
            editValue: [],
            editId: "",
            deleteIsOpen: false,
            sure: false,
            queryId: null
        }
    }

    componentDidMount() {
        const {homeReduce} = this.props;
        const menuType = homeReduce.menusSelected.menuType;
        this.setTable(menuType);
    }

    componentWillReceiveProps(nextProps, nextContext) {
        const {homeReduce} = nextProps;
        const menuType = homeReduce.menusSelected.menuType;
        this.setTable(menuType);
    }

    componentWillUnmount() {
        document.onkeydown = null;
    }

    async inputEnter(e) {
        if (!e) {
            e = window.event
        }
        if ((e.keyCode || e.which) === 13) {
            try {
                const { queryId } = this.state;
                if (queryId === null) {
                    return;
                }
                const {
                    homeReduce
                } = this.props;
                const menuType = homeReduce.menusSelected.menuType;
                const msg = await axios.get(host + menuType + "?" + menuType + "Id=" + queryId)

                if (msg.data.statusCode === 1) {
                    if (msg.data.statusMsg === "") {
                        return
                    }
                    const data = JSON.parse(msg.data.statusMsg);
                    const jsonData = {
                        Key: queryId,
                        Record: data
                    }
                   
                    this.setState({
                        value: HandlePostData([jsonData]),
                        sure: true,
                    })
                }
            } catch (e) {
                console.log(e)
            }
        }
    }

    inputChange(e) {
        this.setState({
            queryId: e.target.value
        })
    }
     
    async setTable(menuType) {
        const msg = await axios.get(host + menuType.toLowerCase() + "/all");
        const json = JSON.parse(msg.data.statusMsg);
        const data = HandlePostData(json);
        this.setState({
            value: data
        })
    }

    handleEditClose() {
        this.setState({
            editIsOpen: false
        })
    }

    handleDeleteClose() {
        this.setState({
            deleteIsOpen: false
        })
    }

    stopBubble(e) {
        e.stopPropagation();
        e.preventDefault();
    }

    editRow(id) {
        const {value} = this.state;
        const {homeReduce} = this.props;
        const menuType = homeReduce.menusSelected.menuType;
        const {inputValue, editAttributes} = handleEditData(value, menuType +"Id", id);
        this.setState({
            editIsOpen: true,
            editAttributes: editAttributes,
            editValue: inputValue,
            editId: id
        })
    }

    deleteRow(id) {
        this.setState({
            deleteIsOpen: true,
            deleteId: id
        })
    }

    async handleDeleteOk(id) {
        const {homeReduce} = this.props;
        const menuType = homeReduce.menusSelected.menuType;
        const obj = {};
        obj[menuType + "Id"] = id;
        try {
            const msg = await axios.post(host + menuType + "/delete", obj)
            if (msg.data.statusCode === 0) {
                AppToaster.show({ message: msg.data.statusInfo });
            } else {
                AppToaster.show({ message: "删除成功" });
            }
        }catch (e) {
            console.log(e)
            AppToaster.show({ message: "发生错误" });
        }
        this.handleDeleteClose();
        this.setTable(menuType);
    }

    setEditDeleteCell(data, rowIndex) {
        const {userReduce} = this.props;
        const edit = userReduce.Permission.edit === "1"
        const dele = userReduce.Permission.delete === "1"
        return (
            <Cell truncated={false}>
                <React.Fragment>
                    <div className="func-edit-delete" onClick={this.stopBubble}>
                        {!!edit && <a role="button" className="bp3-button" tabIndex="0" data-index={data[rowIndex]} onClick={this.editRow.bind(this, data[rowIndex])}>编辑</a>}
                        {!!dele &&  <a role="button" className="bp3-button" tabIndex="0" data-index={data[rowIndex]} onClick={this.deleteRow.bind(this, data[rowIndex])}>删除</a>}
                    </div>
                </React.Fragment>
            </Cell>
        )
    }

    cellRenderer(data, rowIndex) {
        return <Cell>{data[rowIndex]}</Cell>
    }

    setColumn () {
        const {homeReduce} = this.props;
        const menuType = homeReduce.menusSelected.menuType;
        const {value} = this.state;
        const data = value.data;
        const arr = [];
        let FuncComponent = null;
        for (let i in data) {
            const item = data[i];
            if (item.key.toLowerCase()===(menuType.toLowerCase()+"id")) {
                FuncComponent =  <Column key={item.key+"func"} name={"编辑"} cellRenderer={this.setEditDeleteCell.bind(this, item.list)}/>;
            }
            const Component = <Column key={item.key} name={item.key} cellRenderer={this.cellRenderer.bind(this, item.list)}/>;
            arr.push(Component);
        }
        if(FuncComponent) arr.push(FuncComponent);
        return arr;
    }

    render() {
        const {homeReduce} = this.props;
        const menuType = homeReduce.menusSelected.menuType;
        const {value, editIsOpen, editAttributes, editValue, editId, deleteIsOpen, deleteId} = this.state;
        const method = "edit";
        return (
            <div>
                <div className="bp3-input-group .modifier query-search">
                    <input type="text" className="bp3-input"  placeholder="用户Id" onChange={this.inputChange}/>
                    <Icon icon={"search"} iconSize={17} intent={""} />
                </div>
                {
                    !!value && value.length > 0 &&
                    <Table numRows={value.length} defaultRowHeight={30}>
                        {this.setColumn()}
                    </Table>
                }
                {
                    !!editIsOpen && <Edit editAttributes={editAttributes} editValue={editValue} method={method} editId={editId} menuType={menuType} onClose={this.handleEditClose} onOk={this.setTable}/>
                }
                {
                    !!deleteIsOpen && <Delete deleteId={deleteId} onOk={this.handleDeleteOk} onClose={this.handleDeleteClose}/>
                }
            </div>
        );
    }
}

const mapStateToProps = ({ homeReduce, userReduce}) => ({ homeReduce, userReduce});
export default connect(mapStateToProps, homeActions)(TableWrapper);